<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// | 主要是微信登陆在使用
// +----------------------------------------------------------------------
namespace plugins\xiongyi\lib;

use plugins\xiongyi\model\CmfUserModel;
use plugins\xiongyi\model\CmfRoleUserModel;
use plugins\xiongyi\model\CmfThirdPartyUserModel;
use plugins\xiongyi\model\XmglZzjgUserModel;
use think\exception;
use think\facade\Db;

class User
{
    //模型关联方法
    protected $relationFilter = ['user'];

    /**
     * 检查用户，已绑定角色和组织机构返回true，否则返回false
     * @param      $user_id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function checkUserRoleAndZzjg($user_id)
    {
        $xzum = new XmglZzjgUserModel();
        $zzjgList = $xzum->where('user_id','=', $user_id)->find();

        $rum = new CmfRoleUserModel();
        $roleList = $rum->where('user_id','=', $user_id)->find();

        if (empty($zzjgList) || empty($roleList)) {
            return false;
        }
        return true;
    }

    /**
     * 检查用户，user同手机号的，返回true表示已存在，否则返回false
     * @param      $user_id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function checkUserExist($user_login, $mobile, $user_email)
    {
        $cum = new CmfUserModel();
        $user = $cum
            ->whereOr([
                'user_login' => $user_login,
                'mobile' => $mobile,
                'user_email' => $user_email
            ])->find();
        if ($user) return true;
        return false;
    }

    /**
     * web 用户绑定注册
     * @param      $userInfo
     * @return array|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function updateUser($params)
    {
        //dump($params);
        $user_id = 0;
        // 启动事务
        Db::startTrans();
        try {
            //检查user表是否存在同手机号或同email号的用户
            $cum = new CmfUserModel();
            $user = $cum->where([
                'user_login' =>  $params['user_login'],
                'mobile' => $params['mobile'],
                //'user_email' => $params['email'],
            ])->find();
            if ($user) {
                //已经存在这个姓名和手机号的用户了
                $user_id = $user['id'];
                //更新用户数据
                $newUserData = [
                    'birthday'       => $params['birthday'],
                    'sex'            => $params['sex'],
                    'user_email'          => $params['email'],
                    'user_nickname'   => $params['nickname'],
                    'avatar'          => $params['avatar'],
                    'last_login_time' => time(),
                    'last_login_ip'   => get_client_ip(0, true),
                    'create_time'     => time(),
                    "user_type"       => '1',   //1-admin，2-会员
                    'user_pass'       => cmf_password('1+1=2'),    //用户注册后默认密码123456
                ];
                $cum->where('id', $user_id)->update($newUserData);
            } else {
                //没有存在这个姓名和手机号的用户，则新增user
                $newUserData = [
                    'user_login'     => $params['user_login'],
                    'birthday'       => $params['birthday'],
                    'sex'            => $params['sex'],
                    'mobile'         => $params['mobile'],
                    'user_email'          => $params['email'],
                    'user_nickname'   => $params['nickname'],
                    'avatar'          => $params['avatar'],
                    'last_login_time' => time(),
                    'last_login_ip'   => get_client_ip(0, true),
                    'create_time'     => time(),
                    'user_status'     => '2',       //注册后默认需要管理员验证用户
                    "user_type"       => '1',   //1-admin，2-会员
                    'user_pass'       => cmf_password('123456'),    //用户注册后默认密码123456
                ];
                $cum = new CmfUserModel();
                $cum->save($newUserData);
                $user_id =  $cum->id; // 获取自增ID
            }

            if ($user_id == 0) throw new \think\Exception("用户id号错误", 10006);

            $ctpu = new CmfThirdPartyUserModel();
            //检查third_party表是否已有此 openid 和 union_id 的用户
            $third_party_id = $ctpu->where([
                'openid' =>  $params['openid'],
                'union_id' => $params['union_id'],
            ])->find();

            //third_party表,第三方用户表 数据
            $newThirdPartyUserData = [
                'user_id'         => $user_id,
                'last_login_time' => time(),
                'expire_time'     => $params['expire_time'],
                'create_time'     => time(),
                'login_times'     => 1,
                'status'          => 1,
                'nickname'        => $params['nickname'],
                'third_party'     => $params['third_party'],
                'app_id'          => $params['app_id'],                        //本应用固定app_id
                'last_login_ip'   => get_client_ip(0, true),
                'access_token'    => $params['access_token'],
                'openid'          => $params['openid'],
                'union_id'         => $params['union_id'],     //WEB和小程序绑定开放平台后，同一个微信用户union_id是一样的
            ];

            if ($third_party_id) {
                //已经存在这个用户的 openid 和 union_id，则更新数据
                $ctpu->where('id', $third_party_id)->update($newThirdPartyUserData);
            }else{
                //没有，新增third_party表数据
                $ctpu->save($newThirdPartyUserData);
            }

            //转换"zzjgValue":["2","6"]，raw:zzjgValue[]=2&zzjgValue[]=9
            //写入zzjg_user表
            $xzum = new XmglZzjgUserModel();
            //删除原有数据
            $xzum->where('user_id','=',$user_id)->delete();
            $arrzzjg = $params['zzjgValue'];    //取出组织机构数组
            foreach ($arrzzjg as $v) {
                $dzzjg[] = [
                    'user_id' => $user_id,
                    'zzjg_id' => $v
                ];
            }
            //dump($dzzjg);
            $xzum->saveAll($dzzjg);

            //转换"roleValue":["10","3"]，raw:roleValue[]=9&roleValue[]=3&roleValue[]=4
            //写入role_user表
            $rum = new CmfRoleUserModel();
            //删除原有数据
            $rum->where('user_id','=',$user_id)->delete();
            $arrrole = $params['roleValue'];        //取出角色数组
            foreach ($arrrole as $v) {
                $drole[] = [
                    'user_id' => $user_id,
                    'role_id' => $v
                ];
            }
            //dump($drole);
            $rum->saveAll($drole);

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            //var_dump('写数据出错');
            //dump($e->getMessage());
            Db::rollback();
            //return  "写数据出错，" . $e->getMessage();
            throw new \think\Exception("写数据出错，" . $e->getMessage(), 10006);
        }
        return $user_id;
    }
}
